import datetime
import os
import sys
from io import BytesIO
from tkinter import Image

import pytesseract

from selenium import webdriver
from selenium.webdriver import ActionChains, Keys
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from webdriver_manager.chrome import ChromeDriverManager

#配置tesseract路径
pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe'

class Driver:
    drivre = ""

    def __init__(self):
        #创建浏览器驱动对象
        options = webdriver.ChromeOptions()
        self.driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=options)
        self.driver.implicitly_wait(2)

    def GetScreenShot(self):
        #截图功能
        dirname = datetime.datetime.now().strftime("%Y-%m-%d")
        if not os.path.exists(dirname):
            os.mkdir("../image/" + dirname)

        filename = sys._getframe().f_back.f_code.co_name + "-" + datetime.datetime.now().strftime("%Y-%m-%d-%H%M%S") + ".png"

    def clear(self, element):
        #清空指定输入框的内容
        actions = ActionChains(self.driver)
        actions.click(element)
        actions.key_down(Keys.CONTROL).send_keys("a").key_up(Keys.CONTROL)
        actions.send_keys(Keys.DELETE)
        actions.perform()

    def getverifycode(self):
        #获取验证码
        #定位元素
        element = self.driver.find_element(By.CSS_SELECTOR, "#form-verify-img")
        #截图验证码的元素
        img_bytes = element.screenshot_as_png
        img_element = Image.open(BytesIO(img_bytes))
        #用OCR工具识别图片
        #预处理：转为灰度图
        img_element = img_element.convert('L')
        #OCR识别 识别范围：只识别数字
        img_text = pytesseract.image_to_string(
            img_element,
            config="--psm 10 -c tessedit_char_whitelist=0123456789"
        )
        #清洗结果
        img_text = img_text.strip()

        chromeDriver.GetScreenShot()
        return img_text

chromeDriver = Driver()

